package org.example.util;



import org.osgeo.proj4j.*;

import java.text.DecimalFormat;
import java.util.Arrays;

public class CoordinateConversion {

    private static CRSFactory crsFactory = new CRSFactory();
    private static CoordinateTransformFactory ctFactory = new CoordinateTransformFactory();
    static CoordinateReferenceSystem wgs84CRS = crsFactory.createFromName("EPSG:4326");
    static CoordinateReferenceSystem webMercatorCRS = crsFactory.createFromName("EPSG:3857");
    static CoordinateTransform transform = ctFactory.createTransform(wgs84CRS, webMercatorCRS);

    public static double[] transTo3857(double x, double y) {
        try {
            ProjCoordinate p = new ProjCoordinate(x, y); // 例如：经度 10，纬度 50
            transform.transform(p, p);
            return new double[]{p.x, p.y};
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new double[]{0, 0};
    }

    static DecimalFormat decimalFormat = new DecimalFormat("0");

    public static String toPlainNumber(double x) {
        if ((x + "").contains("E") || (x + "").contains("e")) {
            return decimalFormat.format(x);
        } else {
            return x + "";
        }
    }

    public static void main(String[] args) {
//        System.out.println(toPlainNumber(2.9987676));
        double[] a = transTo3857(121.15004696200003, 31.444344019000027);
        System.out.println(Arrays.toString(a));

        String arrStr = "[121.15004696200003, 31.444344019000027, 121.14997162000009, 31.44431416100008, 121.14968742100007, 31.44482028500005, 121.14976290900006, 31.444853116000047, 121.15004696200003, 31.444344019000027]";
        String[] split = arrStr.replace("[", "")
                .replace("]", "")
                .replace(" ", "").split(",");
        double[] points = new double[split.length];
        for (int i = 0; i < split.length; i++) {
            points[i] = Double.parseDouble(split[i]);
        }
        String[] pointsCopy = new String[split.length];
        for (int i = 0; i < points.length; i += 2) {
            double[] res = CoordinateConversion.transTo3857(points[i  ],
                     points[i]);
            pointsCopy[i] = CoordinateConversion.toPlainNumber(res[0]);
            pointsCopy[i + 1] = CoordinateConversion.toPlainNumber(res[1]);
            System.out.println(toPlainNumber(a[0]));
            System.out.println(toPlainNumber(a[1]));
        }
    }
}
